#!/bin/sh

# Startup script for a Cromwell server.
# Place me somewhere accessible (eg /usr/local/bin/cromwell.server) and use 'cromwell.server start' to begin your Cromwell server.

# Cromwell PID:
CROMPID=/usr/local/bin/cromwell/cromwell.pid

# Cromwell jar:
CROMJAR=/usr/local/bin/cromwell/cromwell.jar

# Cromwell conf:
CROMCONF=/etc/cromwell.conf

# Log redirect:
CROMLOG=/usr/local/bin/cromwell/cromwell.log

usage()
{
  echo "Usage: /bin/sh $0 <start|stop|status|logs|config>"
}

status()
{
  VERBOSE=$1
  if [ -f "$CROMPID" ]
    then
      PID=$(cat $CROMPID)
      # Check alive:
      if kill -0 "$PID" >/dev/null 2>&1
      then
        [ "$VERBOSE" = "verbose" ] && echo "Cromwell process running as $PID"
        return 0
      else
        echo "Cromwell was terminated unexpectedly. Removing $CROMPID"
        [ "$VERBOSE" = "verbose" ] && echo "Cromwell is stopped"
        rm $CROMPID
        return 1
      fi
    else
      [ "$VERBOSE" = "verbose" ] && echo "Cromwell is stopped"
      return 1
    fi
}

start()
{
  if status "quiet"
  then
    echo "Cromwell is already running as $(cat $CROMPID)."
    return 1
  else
    CONFOPTION=""
    [ -f "$CROMCONF" ] && CONFOPTION="-Dconfig.file=$CROMCONF"
    java $CONFOPTION -jar $CROMJAR server > $CROMLOG 2>&1 &
    echo $! > $CROMPID
  fi
}

stop()
{
  if status "quiet"
  then
    PID=$(cat $CROMPID)
    SIG=$1
    [ -z "$SIG" ] && SIG=TERM
    if [ -z "${SIG##*[!0-9]*}" ]
    then
      # It's not a number, treat it like a signal name:
      SIG="-s $SIG"
    else
      # It's a number, treat it like a signal ID:
      SIG="-$SIG"
    fi
    echo "kill $SIG \"$PID\""
    if kill $SIG "$PID" >/dev/null 2>&1
    then
      while kill -0 "$PID" >/dev/null 2>&1
      do
        echo "Waiting for Cromwell to exit..."
        sleep 1
      done
      rm $CROMPID
    else
      echo "Unable to kill process $PID using 'kill -s $SIG $PID'"
    fi
  else
    echo "Can't stop Cromwell. Already stopped"
    return 1
  fi
}

MODE=$1
if [ "$MODE" = "start" ]
then
  start
  exit $?
elif [ "$MODE" = "stop" ]
then
  stop "$2"
  exit $?
elif [ "$MODE" = "status" ]
then
  status "verbose"
  exit $?
elif [ "$MODE" = "logs" ]
then
  if [ "$2" = "-t" ]
  then
    tail -f "$CROMLOG"
  else
    cat $CROMLOG
  fi
elif [ "$MODE" = "config" ]
then
  ${EDITOR:-vi} $CROMCONF
else
  usage
  exit 1
fi


